package com.xwqiang.filter;

import com.alibaba.fastjson.JSON;
import com.xwqiang.pojo.model.AuthorSysUser;
import com.xwqiang.utils.ErrCode;
import com.xwqiang.utils.JwtToken;
import com.xwqiang.utils.RedisCache;
import com.xwqiang.utils.Resp;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //实现jwt拦截

        //1.放行一些非JWT请求 /admin/login
        response.setContentType("application/json;charset=utf-8");
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin/login")) {
            filterChain.doFilter(request, response);
            return;
        }


        //3.校验jwt 合法性是否存在 是否能解析 是否超时
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            response.getWriter().write(JSON.toJSONString(Resp.error(ErrCode.JWT_TOKEN_ERR)));
            return;
        }

        if (!JwtToken.isExpired(token)) {
            response.getWriter().write(JSON.toJSONString(Resp.error(ErrCode.EXCEPTION_ERR)));
            return;
        }

        Claims claims = JwtToken.parseJWT(token);
        String id = (String) claims.get("id");
        AuthorSysUser redisUser = redisCache.getCacheObject("authorSysUser:" + id);
        System.out.println(redisUser);
        if (redisUser == null) {
            response.getWriter().write(JSON.toJSONString(Resp.error(ErrCode.JWT_TOKEN_ERR)));
            return;
        }

        UsernamePasswordAuthenticationToken author = new UsernamePasswordAuthenticationToken(
                        redisUser.getUsername(),
                        null,
                        redisUser.getAuthorities());


        SecurityContextHolder.getContext().setAuthentication(author);
        filterChain.doFilter(request, response);
    }
}
